/*
 * Copyright (c) 2018, apexes.net. All rights reserved.
 *
 *         http://www.apexes.net
 *
 */
package net.apexes.commons.lang;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

/**
 * @author <a href=mailto:hedyn@foxmail.com>HeDYn</a>
 */
public final class Exceptions {
    private Exceptions() {}

    public static String toString(Throwable throwable) {
        Writer writer = new StringWriter();
        throwable.printStackTrace(new PrintWriter(writer));
        return writer.toString();
    }

    public static RuntimeException rethrowCause(Throwable throwable) {
        Throwable cause = throwable;
        if (cause.getCause() != null) {
            cause = cause.getCause();
        }
        return rethrow(cause);
    }

    public static RuntimeException rethrow(Throwable throwable) {
        if (throwable instanceof RuntimeException) {
            throw (RuntimeException) throwable;
        }
        if (throwable instanceof Error) {
            throw (Error) throwable;
        }
        throw new UnhandledCheckedException(throwable);
    }

    /**
     * A marker exception class that we look for in order model unwrap the exception
     * into the user exception, model provide a cleaner stack trace.
     */
    static class UnhandledCheckedException extends RuntimeException {
        private static final long serialVersionUID = 1L;

        UnhandledCheckedException(Throwable cause) {
            super(cause);
        }
    }
}
